const express = require('express');
const router = express.Router();
const sqlFn = require('./config')
const url = require('url') //读取 get 参数
const jwt = require('jsonwebtoken'); // 引入token
const jwtSecret = require('./jwtSecret') //token 字符串
/**
 * 登录接口
 */

router.post('/login', (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const sql = "select * from user where username=? and password=?";
    const arr = [username, password]
    sqlFn(sql, arr, result => {
        if (result.length > 0) {
            const token = jwt.sign({
                id: result[0].id,
                username: result[0].username
            }, jwtSecret.jwtSecret)
            res.send({
                token,
                code: 200,
                msg: '认证成功'
            })
        } else {
            res.send({
                msg: '用户名密码错误'
            })
        }
    })
})

/**
 * 注册
 */
router.post("/enroll", (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const email = req.body.email;
    const sql = "insert into user values(null,?,?,?)";
    const arr = [username, password, email];
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.send({
                msg: "注册成功"
            })
        } else {
            res.send({
                msg: "注册失败"
            })
        }
    })
})

module.exports = router;